package com.mnb.base.controller;

import com.google.code.kaptcha.Producer;
import com.mnb.common.utils.Base64;
import com.mnb.common.utils.R;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    private String captchaType = "math";

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public R getCode(HttpServletResponse response, HttpSession session) throws IOException {

        Map map = new HashMap<>();

        // 保存验证码信息
        String uuid = String.valueOf(UUID.randomUUID());

        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        if ("math".equals(captchaType)) {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        } else if ("char".equals(captchaType)) {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        // 将验证码存储到Session中，key为uuid
        session.setAttribute("captcha_" + uuid, code);
        // 设置验证码过期时间（3分钟后）
        session.setAttribute("captcha_expire_" + uuid, System.currentTimeMillis() + 3 * 60 * 1000L);

        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            return R.fail(e.getMessage());
        }

        map.put("uuid", uuid);
        map.put("img", Base64.encode(os.toByteArray()));
        return R.ok(map);
    }
    
    /**
     * 获取验证码（供LoginController调用）
     */
    public static String getCaptcha(HttpSession session, String uuid) {
        String captchaKey = "captcha_" + uuid;
        String expireKey = "captcha_expire_" + uuid;
        
        String captcha = (String) session.getAttribute(captchaKey);
        Long expireTime = (Long) session.getAttribute(expireKey);
        
        if (captcha != null && expireTime != null && expireTime > System.currentTimeMillis()) {
            // 验证码有效，使用后立即删除
            session.removeAttribute(captchaKey);
            session.removeAttribute(expireKey);
            return captcha;
        }
        return null;
    }
}
